import React from 'react';
import { Card, Table, Divider ,Modal, Button, Form, Input, Radio, Icon, message ,DatePicker,Pagination ,Upload ,Select,Spin,Popover } from 'antd';
import { NavLink} from 'react-router-dom';
import moment from 'moment';
import ResizeableTitle from './../../../utils/resizeableTitle';
import Utils from './../../../utils/utils';
import './../../../style/style.css';
import Axios from "../../../axios";
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const Option = Select.Option;
const TextArea = Input.TextArea;

export default class TrainPlanCarryout extends React.Component {
    state = {
        columns: [{
            title: '标题',
            dataIndex: 'title',
            width: 200,
        }, {
            title: '编号',
            dataIndex: 'trainNo',
            width: 150,
        },{
            title: '培训内容',
            dataIndex: 'content',
            width: 200,
        },{
            title: '培训负责人',
            dataIndex: 'principal',
            width: 150,
        },{
            title: '培训老师',
            dataIndex: 'teacher',
            width: 150,
        },{
            title: '培训时间',
            dataIndex: 'trainTime',
            width: 200,
        },{
            title: '培训方式',
            dataIndex: 'type',
            width: 150,
        },{
            title: '培训地点',
            dataIndex: 'location',
            width: 150,
        },{
            title: '备注信息',
            dataIndex: 'remark',
            width: 150,
        },{
            title: '状态',
            dataIndex: 'state',
            width: 100,
            render: (text, record,index) => (
                <span>
                    {record.state == "VALID" ? <span className="txt-success">审批通过</span> : ''}
                    {record.state == "INVALID" ? <span className="txt-danger">审批拒绝</span> : ''}
                    {record.state == "DISABLE" ? <span className="txt-danger">禁用的</span> : ''}
                    {record.state == "DELETE" ? <span className="txt-danger">删除的</span> : ''}
                    {record.state == "WAIT_AUDIT" ? <span className="txt-danger">待审核</span> : ''}
                    {record.state == "UNDER_REVIEW" ? <span className="txt-danger">审核中</span> : ''}
                </span>
            )
        }, {
            title: '操作',
            key: 'action',
            render: (text, record,index) => (
                <span>
                    <NavLink className="btn-txt-primary" to={`/organMember/user/trainPlanCarryoutDetails/${record.id}`}>查看详情</NavLink>
                    {record.state == "VALID" ?
                        <span>
                            <Divider type="vertical" />
                            <a onClick={() => this.handleSignIn(record)} className="btn-txt-primary">签到录入</a>
                        </span>
                        : ''
                    }
                    {record.state == "WAIT_AUDIT" ?
                        <span>
                            <Divider type="vertical" />
                            <a onClick={() => this.handleDel(record)} className="btn-txt-danger">删除</a>
                        </span>
                        : ''
                    }
                    {record.state == "INVALID" ?
                        <span>
                            <Divider type="vertical" />
                            <a onClick={() => this.handleDel(record)} className="btn-txt-danger">删除</a>
                        </span>
                        : ''
                    }
                </span>
            ),
        }],
        createSignInModal:{
            visible: false,
            confirmLoading: false,
        },
    };
    initParams={
        max:10,
        keywords:'',
        page:1,
        state:'',
    }
    componentWillMount(){
        let params = Utils.FilterParam(this.initParams); //过滤掉为空的参数
        this.listRequest(params);
        this.userRequest();//所有用户请求
    }
    //搜索
    handleFilter = (fieldsValue)=>{
        const values = {
            ...fieldsValue,
        };
        console.log(values);
        this.initParams = {
            ...this.initParams,
            ...values,
            page:1
        }
        let params = Utils.FilterParam(this.initParams); //过滤掉为空的参数
        this.listRequest(params)
    }
    //删除
    handleDel = (record)=>{
        Modal.confirm({
            title: '确认删除？',
            content: <div>
                <div>删除后数据不可恢复！</div>
                <div className="txt-danger">确认删除？</div>
            </div>,
            okText:'确认',
            cancelText:'取消',
            onOk:()=>{
                console.log(record.id)
                let params = {
                    id:record.id,
                }
                this.delRequest(params);
            }
        })
    }
    //签到录入 弹窗
    handleSignIn = (record)=>{
        this.setState({
            createSignInModal:{
                ...this.state.createSignInModal,
                visible:true,
                record
            }
        })
    }
    //签到录入 提交
    handleCreateSignInSubmit =()=>{
        const _form = this.createSignInForm.props.form;
        _form.validateFields((err, values) => {
            console.log(values);
            if (err) {
                return;
            }
            console.log(values);
            values.userId = values.userIdName.key;
            values.userName = values.userIdName.label;
            delete values.userIdName;
            let param = Utils.FilterParam(values);
            console.log(param)
            this.createSignInRequest(param);
        });
    }

    /*培训计划实施列表请求*/
    listRequest = (params)=>{
        let _this = this;
        this.setState({
            loading:true,
            loadingTxt:'加载中...'
        })
        Axios.dataRequest({
            block:'/hr',
            url:'/userTrain/train',
            params:params,
        }).then((data)=>{
            console.log(data)
            let page = data.page;
            let dataSource = data.data;
            dataSource.map((item)=>{
                item.key = item.id;
                return item;
            })
            this.setState({
                loading:false,
                dataSource,
                pagination: Utils.pagination(page, (current) => {
                    _this.initParams.page = current;
                    let params = this.initParams;
                    _this.listRequest(params);
                },(current,pageSize) =>{
                    _this.initParams.page = current;
                    _this.initParams.max = pageSize;
                    let params = Utils.FilterParam(this.initParams); //过滤掉为空的参数
                    _this.listRequest(params);
                })
            })
        }).catch((error)=>{
            this.setState({ loading:false })
            console.log(error);
        })
    }
    /*删除请求*/
    delRequest = (params)=>{
        this.setState({
            loading:true,
            loadingTxt:'删除中...'
        })
        Axios.delRequest({
            block:'/hr',
            url:'/userTrain/train',
            params:params,
        }).then((data)=>{
            console.log(data);
            this.setState({ loading:false })
            message.success('删除成功！',2,()=>{
            });
            let _params = Utils.FilterParam(this.initParams); //过滤掉为空的参数
            this.listRequest(_params);
        }).catch((error)=>{
            this.setState({ loading:false })
            console.log(error);
        })
    }
    /*签到录入请求*/
    createSignInRequest = (params)=>{
        this.setState({
            createSignInModal:{
                ...this.state.createSignInModal,
                confirmLoading: true,
            }
        })
        Axios.formRequest({
            block:'/hr',
            url:'/userTrain/trainCheckin',
            params:params,
        }).then((data)=>{
            console.log(data)
            this.setState({
                createSignInModal:{
                    ...this.state.createSignInModal,
                    visible: false,
                    confirmLoading: false,
                }
            })
            message.success('签到录入成功，请到详情查看签到表！',2);
            //window.location.reload()
            //let _params = Utils.FilterParam(this.initParams); //过滤掉为空的参数
            //this.listRequest(_params);
        }).catch((error)=>{
            console.log(error);
            this.setState({
                createSignInModal:{
                    ...this.state.createSignInModal,
                    confirmLoading: false,
                }
            })
        })
    }
    /*所有用户请求*/
    userRequest = ()=>{
        Axios.dataRequest({
            block:'/hr',
            url:'/user/allUserSmallInfos',
            params:"",
        }).then((data)=>{
            console.log(data)
            let users = data.data;
            /*id name userNo*/
            this.setState({
                users,
            })
        }).catch((error)=>{
            console.log(error);
        })
    }

    //伸缩列
    components = {
        header: {
            cell:ResizeableTitle
        },
    };
    handleResize = index => (e, { size }) => {
        this.setState(({ columns }) => {
            const nextColumns = [...columns];
            nextColumns[index] = {
                ...nextColumns[index],
                width: size.width,
            };
            return { columns: nextColumns };
        });
    };
    render() {
        const columns = this.state.columns.map((col, index) => ({
            ...col,
            onHeaderCell: column => ({
                width: column.width,
                onResize: this.handleResize(index),
            }),
        }));
        return (
            <div className="tab-list-box">
                <Spin spinning={this.state.loading} size="large" tip={this.state.loadingTxt}>
                    <Card
                        title="培训计划实施列表"
                        bordered={false}>
                        <div style={{textAlign:'right',marginBottom:15}}>
                            <div className="filter-box" style={{marginBottom:15}}>
                                <FilterForm filterSubmit={(fieldsValue)=>{this.handleFilter(fieldsValue)}}/>
                                {/*<Button type="primary" icon="plus" onClick={this.handleCreate}>创建用户</Button>*/}
                            </div>
                        </div>
                        <Table
                            bordered
                            components={this.components}
                            columns={columns}
                            dataSource={this.state.dataSource}
                            pagination={this.state.pagination}
                        />
                    </Card>
                    <Modal title="添加培训计划实施签到"
                           visible={this.state.createSignInModal.visible}
                           onOk={this.handleCreateSignInSubmit}
                           okText="确定"
                           confirmLoading={this.state.createSignInModal.confirmLoading}
                           destroyOnClose={true}
                           onCancel={()=>{
                               this.setState({
                                   createSignInModal:{
                                       visible:false
                                   }
                               })
                           }}
                    >
                        <CreateSignInForm
                            users={this.state.users}
                            record={this.state.createSignInModal.record}
                            wrappedComponentRef={(createSignInForm)=>{this.createSignInForm = createSignInForm;}}/>
                    </Modal>
                </Spin>
            </div>
        );
    }

}
//添加培训计划实施签到表单
class CreateSignInForm extends React.Component{
    render(){
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: {span: 6},
            wrapperCol: {span: 16}
        };
        const record = this.props.record || {};
        const users = this.props.users || [];
        const userOptions = users.map((item)=>{
            return <Option key={item.id}>{item.name}</Option>;
        });
        return (
            <Form>
                <FormItem label="培训实施编号" {...formItemLayout} style={{display:"none"}}>
                    {
                        getFieldDecorator('trainId',{
                            initialValue:record.id
                        })(
                            <Input type="text" placeholder="培训实施编号"/>
                        )
                    }
                </FormItem>
                <FormItem label="用户" {...formItemLayout}>
                    {
                        getFieldDecorator('userIdName',{
                            rules: [{ required: true, message: '请选择用户!' }],
                        })(
                            <Select
                                placeholder="用户"
                                labelInValue
                                style={{minWidth: 160}}
                                showSearch
                                optionFilterProp="children"
                                filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                            >
                                {userOptions}
                            </Select>
                        )
                    }
                </FormItem>
                <FormItem label="备注" {...formItemLayout}>
                    {
                        getFieldDecorator('remark',{
                        })(
                            <TextArea placeholder="备注" autosize/>
                        )
                    }
                </FormItem>
            </Form>
        );
    }
}
CreateSignInForm = Form.create({})(CreateSignInForm);

//搜索表单
class FilterForm extends React.Component{
    handleFilterSubmit = ()=>{
        let fieldsValue = this.props.form.getFieldsValue();
        this.props.filterSubmit(fieldsValue);
    }
    //重置
    reset = ()=>{
        this.props.form.resetFields();
    }
    render(){
        const { getFieldDecorator } = this.props.form;
        return (
            <Form layout="inline">
                <FormItem label="状态">
                    {
                        getFieldDecorator('state',{
                            initialValue:""
                        })(
                            <Select placeholder="用户状态" style={{minWidth:100}}>
                                <Option key="ALL" value="">全部</Option>
                                <Option key="VALID" value="VALID">审批通过</Option>
                                <Option key="INACTIVE" value="INACTIVE">审批拒绝</Option>
                                <Option key="WAIT_AUDIT" value="WAIT_AUDIT">待审核</Option>
                                <Option key="UNDER_REVIEW" value="UNDER_REVIEW">审核中</Option>
                            </Select>
                        )
                    }
                </FormItem>
                <FormItem label="关键词">
                    {
                        getFieldDecorator('keywords',{
                        })(
                            <Input type="text" placeholder="关键词"/>
                        )
                    }
                </FormItem>
                <FormItem>
                    <Button type="primary" style={{margin:'0 20px'}} onClick={this.handleFilterSubmit}>查询</Button>
                    <Button onClick={this.reset}>重置</Button>
                </FormItem>
            </Form>
        );
    }
}
FilterForm = Form.create({})(FilterForm);